﻿using System.Collections.Generic;
using HDM.NexusEngine.Core;

namespace HDM.NexusEngine.PathFinding
{
    /// <summary>
    /// A navigation mesh is a simple list of convex polygons and the connections between them.
    /// </summary>
    public class NavMesh
    {
        private readonly List<ConvexPolygon> _polygonList = new List<ConvexPolygon>();
        private readonly List<PolygonLink> _links = new List<PolygonLink>();

        public List<ConvexPolygon> PolygonList { get { return _polygonList; } }

        public IEnumerable<PolygonLink> Links { get { return _links; } }

        public void AddPolygon(ConvexPolygon polygon)
        {
            _polygonList.Add(polygon);
        }

        public void AddLink(PolygonLink link)
        {
            _links.Add(link);
        }

        public ConvexPolygon FindNearestPolygon(Point mousePos)
        {
            ConvexPolygon nearestPolygon = null;
            var minDistance = float.MaxValue;

            foreach (var poly in _polygonList)
            {
                var distance = poly.GetClosestEdgeDistance(mousePos);

                if (distance < minDistance)
                {
                    minDistance = distance;
                    nearestPolygon = poly;
                }
            }
            return nearestPolygon;
        }
    }
}